/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on 26 Des 12, 21:13:25
 */
package com.ivanbiz.gui;

import com.ivanbiz.dao.LoginHistoryDAO;
import com.ivanbiz.dao.MenuAksesDAO;
import com.ivanbiz.dao.UserDAO;
import com.ivanbiz.dao.impl.LoginHistoryDAOImpl;
import com.ivanbiz.dao.impl.MenuAksesDAOImpl;
import com.ivanbiz.dao.impl.UserDAOImpl;
import com.ivanbiz.helper.DigiClock;
import com.ivanbiz.helper.GlobalConstant;
import com.ivanbiz.helper.GlobalSession;
import com.ivanbiz.helper.UserSession;
import com.ivanbiz.model.Company;
import com.ivanbiz.model.LoginHistory;
import com.ivanbiz.model.MenuAkses;
import com.ivanbiz.model.User;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

/**
 *
 * @author Administrator
 */
public class MainFrame extends javax.swing.JFrame {

    MenuAksesDAO menuAksesDAO = new MenuAksesDAOImpl();
    User user = UserSession.getUser();
    LoginHistoryDAO loginHistoryDAO = new LoginHistoryDAOImpl();
    UserDAO userDAO = new UserDAOImpl();
    Company company = UserSession.getCompany();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /** Creates new form MainFrame */
    public MainFrame() {
        initComponents();
        updateData();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        treeMenu = new com.ivanbiz.helper.TreeMenu();
        jSplitPane2 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        labelCompanyLogo = new javax.swing.JLabel();
        labelCompanyInfo = new javax.swing.JLabel();
        labelClock = new DigiClock();
        labelCompanyInfo1 = new javax.swing.JLabel();
        labelCompanyInfo2 = new javax.swing.JLabel();
        labelUser = new javax.swing.JLabel();
        desktopPane = new javax.swing.JDesktopPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setExtendedState(MAXIMIZED_BOTH);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jSplitPane1.setDividerLocation(200);

        treeMenu.setFont(new java.awt.Font("Monospaced", 1, 18)); // NOI18N
        treeMenu.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                treeMenuMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(treeMenu);

        jSplitPane1.setLeftComponent(jScrollPane1);

        jSplitPane2.setDividerLocation(100);
        jSplitPane2.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        labelCompanyLogo.setFont(new java.awt.Font("Monospaced", 1, 18)); // NOI18N

        labelCompanyInfo.setFont(new java.awt.Font("Monospaced", 1, 18)); // NOI18N
        labelCompanyInfo.setVerticalAlignment(javax.swing.SwingConstants.TOP);

        labelClock.setFont(new java.awt.Font("Monospaced", 1, 18));

        labelCompanyInfo1.setFont(new java.awt.Font("Monospaced", 1, 18));
        labelCompanyInfo1.setVerticalAlignment(javax.swing.SwingConstants.TOP);

        labelCompanyInfo2.setFont(new java.awt.Font("Monospaced", 1, 18));
        labelCompanyInfo2.setVerticalAlignment(javax.swing.SwingConstants.TOP);

        labelUser.setFont(new java.awt.Font("Monospaced", 1, 18));
        labelUser.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(labelCompanyLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(labelCompanyInfo2, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE)
                    .addComponent(labelCompanyInfo1, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE)
                    .addComponent(labelCompanyInfo, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(labelUser, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
                    .addComponent(labelClock, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(labelCompanyLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(labelCompanyInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelCompanyInfo1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelCompanyInfo2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(labelUser, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(labelClock, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jSplitPane2.setTopComponent(jPanel1);
        jSplitPane2.setRightComponent(desktopPane);

        jSplitPane1.setBottomComponent(jSplitPane2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 293, Short.MAX_VALUE)
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-408)/2, (screenSize.height-327)/2, 408, 327);
    }// </editor-fold>//GEN-END:initComponents

    private void treeMenuMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_treeMenuMouseClicked
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    if (desktopPane != null) {
                        desktopPane.removeAll();
                        desktopPane.repaint();
                    }
                    String menuName = treeMenu.getSelectionPath().getLastPathComponent().toString();
                    if (!menuName.equalsIgnoreCase(GlobalConstant.LOGOUT)) {
                        MenuAkses menuAkses = (MenuAkses) menuAksesDAO.getDataByEqual(MenuAkses.class, "nama", menuName);
                        JInternalFrame internalFrame = (JInternalFrame) Class.forName(menuAkses.getPath()).newInstance();
                        GlobalSession.setDesktopsize(desktopPane.getSize());
                        internalFrame.setSize(desktopPane.getSize());
                        internalFrame.setTitle(menuAkses.getNama());
                        desktopPane.add(internalFrame);
                    } else {
                        int response = JOptionPane.showConfirmDialog(null, GlobalConstant.MSG_LOGOUT, GlobalConstant.CONFIRM, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        if (response == JOptionPane.YES_OPTION) {
                            logoutHistory(user);
                            LoginFrame loginFrame = new LoginFrame();
                            loginFrame.setVisible(true);
                            setVisible(false);
                        }
                    }
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, ex.getMessage());
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }//GEN-LAST:event_treeMenuMouseClicked

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        try {
            user.setIsLogin(GlobalConstant.N);
            userDAO.update(user);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            logoutHistory(user);
            System.exit(0);
        }
    }//GEN-LAST:event_formWindowClosing
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JDesktopPane desktopPane;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JSplitPane jSplitPane2;
    private javax.swing.JLabel labelClock;
    private javax.swing.JLabel labelCompanyInfo;
    private javax.swing.JLabel labelCompanyInfo1;
    private javax.swing.JLabel labelCompanyInfo2;
    private javax.swing.JLabel labelCompanyLogo;
    private javax.swing.JLabel labelUser;
    private javax.swing.JTree treeMenu;
    // End of variables declaration//GEN-END:variables

    private void updateData() {
        if (company != null) {
            String telp = null;
            String fax = null;
            telp = company.getTelp() == null ? GlobalConstant.TELP + GlobalConstant.MIN : GlobalConstant.TELP + company.getTelp();
            fax = company.getFax() == null ? GlobalConstant.FAX + GlobalConstant.MIN : GlobalConstant.FAX + company.getFax();
            labelCompanyInfo.setText(company.getNama());
            labelCompanyInfo1.setText(company.getAlamat());
            labelCompanyInfo2.setText(telp + GlobalConstant.SPACE + fax);
            labelCompanyLogo.setIcon(new ImageIcon(company.getLogo() == null ? GlobalConstant.EMPTY_STRING : company.getLogo()));
            this.setTitle(company.getNama());
            labelUser.setText(GlobalConstant.WELCOME + GlobalConstant.SPACE + user.getKaryawan().getNama());
        }
    }

    private void logoutHistory(User user) {
        try {
            List<LoginHistory> listLoginHistory = loginHistoryDAO.getDataByEquals(LoginHistory.class, "user.id", user.getId(), "dateKeluar", GlobalConstant.N);
            for (LoginHistory loginHistory : listLoginHistory) {
                loginHistory.setDateKeluar(simpleDateFormat.format(new Date()));
                loginHistoryDAO.update(loginHistory);
            }
        } catch (Exception ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
